<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>随机验证码校验</title>
</head>
<body>
    <div id="code" style="height: 20px;"></div>
    <input type="text" id="newCode">
    <input type="button" id="validate" value="验证">

    <script>
        window.onload = function(){
            var code;
            var codeDiv = document.getElementById("code");
            var newCodeInput = document.getElementById('newCode');
            var validate = document.getElementById('validate');
            var vvalue;
            createCode();
            function random(min,max){
                return Math.floor(Math.random()*(max-min)+min);
            }
            function createCode(){
                code = '';
                var codelength = 4;
                var randomCode = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
                for(var i = 0;i < codelength;i++){
                    var index = random(0,36);
                    code+= randomCode[index];
                }
                console.log(code);
                
                codeDiv.innerHTML = code;
            }
            validate.onclick = function(){
                vvalue = newCodeInput.value;
                if(vvalue == code){
                    alert('验证码正确');
                    window.location.href = '#';
                }else{
                    alert('验证码错误');
                    //输入框置空
                    newCodeInput.value = '';
                    //重新生成验证码
                    createCode();
                }
            }

        }
    </script>
</body>
</html>